package com.kalemao.library.http;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.kalemao.library.base.MResponse;
import com.kalemao.library.base.RunTimeData;
import com.kalemao.library.http.api.UploadService;
import com.kalemao.library.logutils.okhttplog.KLMHttpLoggingInterceptor;
import com.kalemao.library.logutils.okhttplog.LogInterceptor;
import com.kalemao.library.utils.upload.MyHttpLoggingInterceptor;
import java.security.cert.CertificateException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

/**
 * 网络请求地址配置类
 *
 * Created by dim on 2017/5/19 14:03 邮箱：271756926@qq.com
 */

public class BaseNetWork {
    /**
     * 测试
     */
    public static final String IP_FOR_HALIAEETUS = "http://nat.ishangchao.cn/api/";

    public static OkHttpClient okHttpClient;

    /**
     * 是否需要打印请求的log日志，可以通过genericClientForLog（）设置开关
     */
    private static boolean mDoesNeedLog = false;

    protected static BaseNetWork instance;

    public static BaseNetWork getInstance() {
        if (instance == null) {
            instance = new BaseNetWork();
        }
        return instance;
    }

    /**
     * 用于httphead改变之后，刷新请求数据头的信息
     *
     * @author dim.
     * @time 2017/11/15 11:00.
     */
    public void afterHttpHeadChanged() {
        okHttpClient = null;
        onHttpheadChanged();
    }

    /**
     * 当请求头信息修改之后，对应的App若有需要修改的可通过此方法做对应的操作
     *
     * @author dim.
     * @time 2017/11/15 11:01.
     */
    protected void onHttpheadChanged() {
    }

    /**
     * 是否需要打开http请求的日志，并且重新new client
     */
    public void genericClientForLog(boolean doesNeedLog) {
        // 如果和当前的日志开关一样，那么不设置
        if (mDoesNeedLog == doesNeedLog) {
            return;
        }
        if (okHttpClient != null) {
            okHttpClient = null;
        }
        mDoesNeedLog = doesNeedLog;
        genericClient();
    }

    public OkHttpClient genericClient() {
        if (okHttpClient != null) {
            return okHttpClient;
        }
        KLMHttpLoggingInterceptor interceptor = new KLMHttpLoggingInterceptor(new LogInterceptor(),
                                                                              RunTimeData.getInstance().getHttpHead());
        if (mDoesNeedLog) {
            interceptor.setLevel(KLMHttpLoggingInterceptor.Level.BODY);
        } else {
            interceptor.setLevel(KLMHttpLoggingInterceptor.Level.NONE);
        }
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(interceptor);

        // 自定义一个信任所有证书的TrustManager，添加SSLSocketFactory的时候要用到
        final X509TrustManager trustAllCert = new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        };
        final SSLSocketFactory sslSocketFactory = new SSLSocketFactoryCompat(trustAllCert,
                                                                             RunTimeData.getInstance().getmContext());
        builder.sslSocketFactory(sslSocketFactory, trustAllCert);

        builder.build();
        okHttpClient = builder.build();
        return okHttpClient;
    }

    /**
     * 获取对应的API
     *
     * @author dim.
     * @time 2017/11/15 11:02.
     */
    public Object getApi(Class apiClass, String baseIp, Object typeAdapter) {
        Gson gson = new GsonBuilder().registerTypeAdapter(MResponse.class, typeAdapter).create();
        Retrofit retrofit = new Retrofit.Builder().client(genericClient()).baseUrl(baseIp).addConverterFactory(
                GsonConverterFactory.create(gson)).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
        return retrofit.create(apiClass);
    }

    /**
     * 获取上传参数
     */
    public UploadService getUploadApi(String baseIp) {
        Retrofit retrofit = new Retrofit.Builder().client(getUploadClient()).baseUrl(baseIp).addConverterFactory(
                SimpleXmlConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
        return retrofit.create(UploadService.class);
    }

    private OkHttpClient getUploadClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        MyHttpLoggingInterceptor interceptor = new MyHttpLoggingInterceptor().setLevel(
                MyHttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(interceptor);
        builder.build();
        return builder.build();
    }
}